package com.liwen.service.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;

/**
 * mybits配置
 */
@Configuration
@EnableTransactionManagement
@MapperScan(value = {"com.liwen.dao.mapper"}, sqlSessionFactoryRef = "sqlSessionFactoryBean")
public class DruidConfig extends AppConfig {

    /**
     * 获取前缀
     *
     * @return
     */
    @Override
    protected String prefix() {
        return "datasource.";
    }

    @Bean("dataSource")
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(getStr("url"));
        datasource.setDriverClassName(getStr("driver-class-name"));
        datasource.setUsername(getStr("username"));
        datasource.setPassword(getStr("password"));

        datasource.setInitialSize(Integer.parseInt(getStr("druid.initial-size")));
        datasource.setMinIdle(Integer.parseInt(getStr("druid.min-idle")));
        datasource.setMaxWait(Long.parseLong(getStr("druid.max-wait")));
        datasource.setMaxActive(Integer.parseInt(getStr("druid.max-active")));
        datasource.setMinEvictableIdleTimeMillis(Long.parseLong(getStr("druid.min-evictable-idle-time-millis")));
        try {
            datasource.setFilters("common,wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return datasource;
    }

    /**
     * mybatis xml扫描配置类
     *
     * @param dataSource
     * @return
     */
    @Bean("sqlSessionFactoryBean")
    public SqlSessionFactoryBean SqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) throws IOException {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mappings/*.xml"));
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setCacheEnabled(false);
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        return bean;
    }
}
